<template>
  <div class="app-container">
    <h2 style="text-align: center">发布新课程</h2>

    <el-steps
      :active="1"
      process-status="wait"
      align-center
      style="margin-bottom: 40px"
    >
      <el-step title="填写课程基本信息" />
      <el-step title="创建课程大纲" />
      <el-step title="最终发布" />
    </el-steps>

    <el-form label-width="120px">
      <el-form-item label="课程标题">
        <el-input
          v-model="courseInfo.title"
          placeholder=" 示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写"
        />
      </el-form-item>

      <!-- 所属分类 TODO -->
      <!-- 所属分类：级联下拉列表 -->
      <!-- 一级分类 -->
      <el-form-item label="课程类别">
        <el-select
          v-model="courseInfo.subjectParentId"
          placeholder="一级分类"
          @change="subjectLevelOneChanged"
        >
          <el-option
            v-for="subject in subjectOneList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id"
          />
        </el-select>
        <!-- 二级分类 -->
        <el-select v-model="courseInfo.subjectId" placeholder="二级分类">
          <el-option
            v-for="subject in subjectTwoList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id"
          />
        </el-select>
      </el-form-item>

      <!-- 课程讲师 -->
      <el-form-item label="课程讲师">
        <el-select v-model="courseInfo.teacherId" placeholder="请选择">
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.id"
            :label="teacher.name"
            :value="teacher.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="总课时">
        <el-input-number
          :min="0"
          v-model="courseInfo.lessonNum"
          controls-position="right"
          placeholder="请填写课程的总课时数"
        />
      </el-form-item>

      <!-- 课程简介 TODO -->
      <!-- 课程简介-->
      <el-form-item label="课程简介">
        <tinymce :height="300" v-model="courseInfo.description" />
      </el-form-item>

      <!-- 课程封面-->
      <el-form-item label="课程封面">
        <el-upload
          v-loading="listLoading"
          element-loading-text="图片上传中"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :action="BASE_API + '/eduoss/fileoss'"
          class="avatar-uploader"
        >
          <img :src="courseInfo.cover" />
        </el-upload>
      </el-form-item>

      <el-form-item label="课程价格">
        <el-input-number
          :min="0"
          v-model="courseInfo.price"
          controls-position="right"
          placeholder="免费课程请设置为0元"
        />
        元
      </el-form-item>

      <el-form-item>
        <el-button
          :disabled="saveBtnDisabled"
          type="primary"
          @click="saveOrUpdate"
          >保存并下一步</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import course from "@/api/edu/course";
import subject from "@/api/edu/subject";
import Tinymce from "@/components/Tinymce"; //引入组件

export default {
  //声明组件
  components: { Tinymce },
  data() {
    return {
      saveBtnDisabled: false, // 保存按钮是否禁用
      courseInfo: {
        //课程信息
        title: "",
        subjectId: "", //二级分类id
        subjectParentId: "", //一级分类id
        teacherId: "",
        lessonNum: 0,
        description: "",
        cover: "",
        price: 0,
      },
      teacherList: [], //下拉列表中的讲师
      subjectOneList: [], //一级分类列表
      subjectTwoList: [], //二级分类列表
      BASE_API: process.env.BASE_API, // 接口API地址
      courseId: "", //课程id
      listLoading: false, //是否显示图片上传中这几个字
    };
  },
  created() {
    this.init();
  },
  watch: {
    $route(to, from) {
      this.init();
    },
  },
  methods: {
    //初始化方法
    init() {
      if (this.$route.params && this.$route.params.id) {
        //修改操作
        this.courseId = this.$route.params.id;
        //调用回显方法
        this.getCourseInfo();
        //初始化讲师下拉列表
        this.getTeacherList();
      } else {
        //添加操作
        //清空表单
        this.courseInfo = {};
        this.courseInfo.lessonNum = 0;
        this.courseInfo.price = 0;
        //设置默认封面
        this.courseInfo.cover =
          "https://edu-fosss.oss-cn-beijing.aliyuncs.com/%E9%BB%98%E8%AE%A4%E5%A4%B4%E5%83%8F%E5%95%A5%E7%9A%84/%E8%AF%BE%E7%A8%8B%E9%BB%98%E8%AE%A4%E5%B0%81%E9%9D%A2.jpg";
        //调用下拉列表方法
        this.getTeacherList();
        //初始化一级分类
        this.getOneSubject();
      }
    },

    //课程回显
    getCourseInfo() {
      course.getCourseInfo(this.courseId).then((res) => {
        this.courseInfo = res.data.courseInfoVo;
        //============一下为解决回显时二级分类无法显示的操作========
        //获取所有的一级分类，遍历找到该课程的一级分类
        subject.getSubjectList().then((res) => {
          this.subjectOneList = res.data.list;
          for (var i = 0; i < this.subjectOneList.length; i++) {
            var oneSubject = this.subjectOneList[i];
            if (oneSubject.id == this.courseInfo.subjectParentId) {
              //获取并设置该一级分类的二级分类
              this.subjectTwoList = oneSubject.children;
            }
          }
        });
      });
    },

    //上传成功调用的方法
    handleAvatarSuccess(res) {
      this.courseInfo.cover = res.data.url;
      this.listLoading = false;
    },
    //上传之前调用的方法
    beforeAvatarUpload(file) {
      this.listLoading = true;
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }

      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    //根据一级分类获取相应的二级分类
    subjectLevelOneChanged(id) {
      //这里的id就是一级分类的id
      //遍历一级分类，找到该id的一级分类
      for (var i = 0; i < this.subjectOneList.length; i++) {
        var oneSubject = this.subjectOneList[i];
        if (id === oneSubject.id) {
          this.subjectTwoList = oneSubject.children;
          //将二级分类id清空，避免更换一级分类时上一个的二级分类仍然存在
          this.courseInfo.subjectId = "";
        }
      }
    },
    //显示一级分类
    getOneSubject() {
      subject.getSubjectList().then((res) => {
        this.subjectOneList = res.data.list;
      });
    },
    //添加课程
    addCourse() {
      course.saveCourse(this.courseInfo).then((res) => {
        this.$message({
          type: "success",
          message: "添加课程成功!",
        });
        this.$router.push({ path: "/course/chapter/" + res.data.courseId });
      });
    },
    //修改课程
    updateCourse() {
      course.updateCourseInfo(this.courseInfo).then((res) => {
        this.$message({
          type: "success",
          message: "修改课程成功!",
        });
        this.$router.push({ path: "/course/chapter/" + this.courseId });
      });
    },

    //添加或修改课程
    saveOrUpdate() {
      if (this.courseInfo.id) {
        //courseInfo有id,则调用修改方法
        this.updateCourse();
      } else {
        this.addCourse();
      }
    },
    getTeacherList() {
      course.getTeachers().then((res) => {
        this.teacherList = res.data.items;
      });
    },
  },
};
</script>

// 组件样式
<style scoped>
.tinymce-container {
  line-height: 29px;
}
</style>